package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.form.impl.FootTeamSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootTeamMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service("footTeamService")
public class FootTeamServiceImpl extends ServiceImpl<FootTeam> implements FootTeamService {
	//初始资金是多少
	public static final double CSZJ = 100D;
    private List<FootClub> alllist = new ArrayList<>();
    private List<FootClub> temp = new ArrayList<>();

    @Autowired
    private FootTeamMapper footTeamMapper;
	@Autowired
	private FootUserService footUserService;
	@Autowired
	private FootUserPersonService footUserPersonService;
	@Autowired
	private FootClubService footClubService;
	@Autowired
	private FootRankService footRankService;
	@Autowired
	private FootChipService footChipService;
	@Autowired
	private FootZnxService footZnxService;
	@Autowired
	private FootZjService footZjService;
	@Autowired
	private FootQdService footQdService;

    /**
     * 更新非空字段
     * @param entity 参数
     * @param request 参数
     * @return 返回值
     */
    @Override
    @Transactional
    @SystemServiceLog(description = "更新非空字段")
    public int updateNotNull(FootTeam entity, HttpServletRequest request){
        FootTeam team = this.get(entity.getId());
        if(team != null){
            team.setQdZzj(team.getQdZzj() + entity.getQdZzj());
            footZnxService.sendZnx(footUserService.getAdminUserid(), team.getUserId(),
                    entity.getYy(), null, null, request);
        }
        return super.updateNotNull(team, request);
    }

    /**
     * 根据用户id找team
     * @param userId 用户主键
     * @return 球队信息
     */
	@Override
	public FootTeam getTeamByUserid(Long userId){
	    return footTeamMapper.findByUserId(userId);
	}

    /**
     * 找出赛季常规赛的前top - buttom名
     * @param sjid 赛季编码
     * @param top 第一
     * @param buttom 最后
     * @return 球队列表
     */
	@Override
	public List<FootTeam> findTopClub(Long sjid, Integer top, Integer buttom) {
		List<FootClub> list = footClubService.findTopClub(sjid, top, buttom);
		List<FootTeam> teams = new ArrayList<>();
		if(list != null && !list.isEmpty()){
			for(FootClub club: list){
				teams.add(this.getTeamByUserid(club.getUserId()));
			}
		}
		return teams;
	}

    /**
     * 是否破产
     * @param request 请求
     */
	@Override
	@Transactional
	public void isPc(HttpServletRequest request) {
		Example example = new Example(FootTeam.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andLessThan("qdZzj", 0D);
		List<FootTeam> list = this.findall(example);
		if(list == null || list.isEmpty()) {
			return;
		}
		for(FootTeam ft: list){
			List<FootPerson> fplist = footUserPersonService.findFootPersonByUserId(ft.getUserId(), request);
			double result = ft.getQdZzj();
            lockUser(result, ft, request);
            //解约最贵球员,并返回80%身价
            if(result <= 0){
                processNoMoney(result, fplist, ft, request);
            }
		}
	}

	private void lockUser(double result, FootTeam ft, HttpServletRequest request){
        //锁定用户不让登陆
        if(result < 0){
            FootUser user = footUserService.get(ft.getUserId());
            user.setSd(true);
            footUserService.updateNotNull(user, request);
        }
    }

	private void processNoMoney(double result, List<FootPerson> fplist, FootTeam ft, HttpServletRequest request){
        //解约最贵球员,并返回80%身价
        Double totalMoney = 0D;
        for(FootPerson fp: fplist){
            footUserPersonService.deletePersonFromMyTeam(ft.getUserId(), fp.getId(), null, request);
            totalMoney = result + Double.valueOf(fp.getQysj()) * 0.8D;
            if(totalMoney >= 0) {
                break;
            }
        }
        ft.setQdZzj(totalMoney);
        this.updateNotNull(ft, request);
    }

	/*  赛季奖金发放
	 * 	明日之星		胜率>=20%		10	绿色碎片1个
	 *	初露锋芒		胜率>=50%		10	绿色碎片3个
	 *	领头羊		胜率>=80%		20	蓝色碎片3个
	 *	灵敏嗅觉		进球>=50个		10	蓝色碎片3个
	 *	百发百中		进球>=100个		20	蓝色碎片6个
	 *	固若金汤		失球总数最少		20	紫色碎片3个
	 *	无坚不摧		进球总数最多		20	紫色碎片3个
	 *	铁人			场次达到30场		20	蓝色碎片3个   紫色碎片1个
	 *	巅峰之战		常规赛冠军		30	紫色碎片*3
	 *	差之毫厘		常规赛亚军		20	紫色碎片*2
	 *	再接再厉		常规赛季军		10	紫色碎片*1
	 *	大满贯		进球最多，失球最少	50	紫色碎片3个 橙色碎片2个
	 *	宇宙第一		完成所有赛季任务	100	紫色碎片5个  橙色碎片3个
	 */
	@Override
	public void fjl(Long sj, boolean isRank, HttpServletRequest request) {
		if(isRank){
			//排位赛前三名
            processTop3Win(request);
		}else{
			//明日之星
            processStar(sj, request);
            //初露锋芒
            processFirst(sj, request);
            //领头羊
            processTopSheep(sj, request);
            //灵敏嗅觉
            processSmell(sj, request);
            //百发百中
			processMadeIt(sj, request);
            //固若金汤
			processDefenceTop(sj, request);
            //无坚不摧
			processAttackTop(sj, request);
            //铁人
			processIronMan(sj, request);
            //巅峰之战 1-3
			processTop1(request);
            processTop2(request);
            processTop3(request);
            //宇宙第一
            processAlwaysFirst(request);
		}
	}

    private void processTop3Win(HttpServletRequest request){
        //排位赛前三名
        List<FootRank> list = footRankService.getScoreboard();
        if(list != null && list.size() > 3){
            this.getRankEndMoney(list.get(0), "冠军", 30, request);
            this.getRankEndMoney(list.get(1), "亚军", 20, request);
            this.getRankEndMoney(list.get(2), "季军", 10, request);
        }
    }

    private void processStar(Long sj, HttpServletRequest request){
        List<FootClub> list = footClubService.getWinClubsBySj(4, sj);
        for(FootClub club: list){
            temp.add(club);
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 10D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveGreen(chip.getHaveGreen() + 1L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            //站内信 资金变动
            String result = "完成明日之星任务,获得奖励：10PB 绿色碎片1个 ";
            footZjService.sendZj(club.getUserId(), 10D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
    }

    private void processFirst(Long sj, HttpServletRequest request){
        List<FootClub> list2 = footClubService.getWinClubsBySj(5, sj);
        for(FootClub club: list2){
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 10D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveGreen(chip.getHaveGreen() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成初露锋芒任务,获得奖励：10PB 绿色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 10D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processTopSheep(Long sj, HttpServletRequest request){
        List<FootClub> list3 = footClubService.getWinClubsBySj(6, sj);
        for(FootClub club: list3){
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 20D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveBlue(chip.getHaveBlue() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成领头羊任务,获得奖励：20PB 蓝色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processSmell(Long sj, HttpServletRequest request) {
        List<FootClub> list4 = footClubService.getWinClubsBySj(7, sj);
        for(FootClub club: list4){
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 10D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveBlue(chip.getHaveBlue() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成灵敏嗅觉任务,获得奖励：10PB 蓝色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 10D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processMadeIt(Long sj, HttpServletRequest request) {
        List<FootClub> list5 = footClubService.getWinClubsBySj(8, sj);
        for(FootClub club: list5){
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 20D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveBlue(chip.getHaveBlue() + 6L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成百发百中任务,获得奖励：20PB 蓝色碎片6个 ";
            footZjService.sendZj(club.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processDefenceTop(Long sj, HttpServletRequest request) {
        List<FootClub> list6 = footClubService.getWinClubsBySj(1, sj);
        if(list6 != null && !list6.isEmpty()){
            FootClub club = list6.get(0);
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 20D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHavePurple(chip.getHavePurple() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成固若金汤任务,获得奖励：20PB 紫色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processAttackTop(Long sj, HttpServletRequest request) {
        List<FootClub> list7 = footClubService.getWinClubsBySj(2, sj);
        if(list7 != null && !list7.isEmpty()){
            FootClub club = list7.get(0);
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 20D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHavePurple(chip.getHavePurple() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成无坚不摧任务,获得奖励：20PB 紫色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processIronMan(Long sj, HttpServletRequest request) {
        List<FootClub> list8 = footClubService.getWinClubsBySj(3, sj);
        for(FootClub club: list8){
            if(temp.contains(club)){
                alllist.add(club);
            }
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 20D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHaveBlue(chip.getHaveBlue() + 3L);
                chip.setHavePurple(chip.getHavePurple() + 1L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成铁人任务,获得奖励：20PB 蓝色碎片3个和紫色碎片1个 ";
            footZjService.sendZj(club.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        temp = alllist;
        alllist.clear();
    }

    private void processTop1(HttpServletRequest request) {
        FootClub top1 = footClubService.getTopClubBySj(1);
        if(null != top1){
            if(temp.contains(top1)){
                alllist.add(top1);
            }
            FootTeam top1team = this.getTeamByUserid(top1.getUserId());
            top1team.setQdZzj(top1team.getQdZzj() + 30D);
            FootChip top1chip = footChipService.findChipByUserId(top1.getUserId());
            if(null != top1chip){
                top1chip.setHavePurple(top1chip.getHavePurple() + 3L);
                footChipService.updateNotNull(top1chip, request);
            }
            this.updateNotNull(top1team, request);
            String result = "完成巅峰之战任务,获得奖励：30PB 紫色碎片3个 ";
            footZjService.sendZj(top1.getUserId(), 30D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), top1.getUserId(), result,
                    null, null, request);
        }
        temp.clear();
        alllist.clear();
    }

    private void processTop2(HttpServletRequest request) {
        FootClub top2 = footClubService.getTopClubBySj(2);
        if(null != top2){
            FootTeam top2team = this.getTeamByUserid(top2.getUserId());
            top2team.setQdZzj(top2team.getQdZzj() + 20D);
            FootChip top2chip = footChipService.findChipByUserId(top2.getUserId());
            if(null != top2chip){
                top2chip.setHavePurple(top2chip.getHavePurple() + 2L);
                footChipService.updateNotNull(top2chip, request);
            }
            this.updateNotNull(top2team, request);
            String result = "完成差之毫厘任务,获得奖励：20PB 紫色碎片2个 ";
            footZjService.sendZj(top2.getUserId(), 20D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), top2.getUserId(), result,
                    null, null, request);
        }
    }

    private void processTop3(HttpServletRequest request) {
        FootClub top3 = footClubService.getTopClubBySj(3);
        if(null != top3){
            FootTeam top3team = this.getTeamByUserid(top3.getUserId());
            top3team.setQdZzj(top3team.getQdZzj() + 10D);
            FootChip top3chip = footChipService.findChipByUserId(top3.getUserId());
            if(null != top3chip){
                top3chip.setHavePurple(top3chip.getHavePurple() + 1L);
                footChipService.updateNotNull(top3chip, request);
            }
            this.updateNotNull(top3team, request);
            String result = "完成再接再厉任务,获得奖励：10PB 紫色碎片1个 ";
            footZjService.sendZj(top3.getUserId(), 10D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), top3.getUserId(), result,
                    null, null, request);
        }
    }

    private void processAlwaysFirst(HttpServletRequest request) {
        //宇宙第一 算法
        for(FootClub club: alllist){
            FootTeam team = this.getTeamByUserid(club.getUserId());
            team.setQdZzj(team.getQdZzj() + 100D);
            FootChip chip = footChipService.findChipByUserId(club.getUserId());
            if(null != chip){
                chip.setHavePurple(chip.getHavePurple() + 5L);
                chip.setHaveOrange(chip.getHaveOrange() + 3L);
                footChipService.updateNotNull(chip, request);
            }
            this.updateNotNull(team, request);
            String result = "完成宇宙第一任务,获得奖励：100PB 紫色碎片5个  橙色碎片3个 ";
            footZjService.sendZj(club.getUserId(), 10D, true, result, request);
            footZnxService.sendZnx(footUserService.getAdminUserid(), club.getUserId(), result,
                    null, null, request);
        }
    }

	/**
	 * 给排位赛发奖励了
	 * @param footRank 排位实体
	 * @param mc 名次
	 * @param money 获得的奖励金额
     * @param request 请求
	 */
	private void getRankEndMoney(FootRank footRank, String mc, double money, HttpServletRequest request) {
		if(footRank != null){
			FootTeam team = this.getTeamByUserid(footRank.getUserId());
			if(null != team){
				team.setQdZzj(team.getQdZzj() + money);
				this.updateNotNull(team, request);
				String result = "获得排位赛" + mc + "奖励：" + money + "PB";
				footZjService.sendZj(team.getUserId(), money, true, result, request);
				footZnxService.sendZnx(footUserService.getAdminUserid(), team.getUserId(), result,
						null, null, request);
			}
		}
	}

    /**
     * 根据用户主键获取图片
     * @param userId 用户主键
     * @return 图片主键
     */
	@Override
	public Long getLogoByUserid(Long userId) {
		FootTeam team = this.getTeamByUserid(userId);
		if(null != team && team.getId() != null){
			FootQd qd = footQdService.get(team.getId());
			if(null != qd){
				return qd.getLogo();
			}
		}
		return null;
	}

    /**
     * 根据用户主键获取缩略图
     * @param userId 用户主键
     * @return 缩略图主键
     */
	@Override
	public Long getSltByUserid(Long userId) {
		FootTeam team = this.getTeamByUserid(userId);
		if(null != team && !StringUtils.isEmpty(team.getId())){
			FootQd qd = footQdService.get(team.getId());
			if(null != qd){
				return qd.getSlt();
			}
		}
		return null;
	}

    /**
     * 保存球队信息
     * @param user 用户
     * @param qdId 球队主键
     * @param request 请求
     */
	@Override
	public void saveNewTeam(FootUser user, Long qdId, HttpServletRequest request) {
		FootTeam ft = new FootTeam();
		ft.setQdId(qdId);
		ft.setQdZzj(0D);
		ft.setUserId(user.getId());
		this.save(ft, request);
		//初始资金分配
		this.createZjTeamByUserId(user.getId(), qdId, null, request);
	}

    /**
     * 创建球队的资金初始值
     * @param userId 用户主键
     * @param qdId 球队主键
     * @param qdmc 球队名称
     * @param request 请求
     */
	@Override
	public void createZjTeamByUserId(Long userId, Long qdId, String qdmc, HttpServletRequest request) {
        FootTeam team = this.getTeamByUserid(userId);
		if(team != null){
            if(null != qdId){
                team.setQdId(qdId);
            }
			if(null != qdmc){
				team.setQdName(qdmc);
			}
			team.setQdZzj(CSZJ);
			this.updateNotNull(team, request);
			footZjService.sendZj(userId, CSZJ, true, "因分配球队获得常规赛初始资金€" +
					new DecimalFormat(",###").format(CSZJ) + ",当前球队的总资金为:€" + 
					new DecimalFormat(",###").format(team.getQdZzj()), request);
			footZnxService.sendZnx(footUserService.getAdminUserid(), userId, "已分配" + team.getQdName() +
					"给玩家,可以继续游戏", null, null, request);
		}
	}

    /**
     * 根据球队主键获取记录列表
     *
     * @param qdId 球队主键
     * @return 列表
     */
    @Override
    public List<FootTeam> findTeamByQdId(Long qdId) {
        Example example = new Example(FootTeam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("qdId", qdId);
        return this.findall(example);
    }

    /**
     * 翻页方法
     *
     * @param footTeamSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootTeam> findall(FootTeamSearchForm footTeamSearchForm) {
        return footTeamMapper.findall(footTeamSearchForm);
    }

    /**
     * 根据主键获取记录
     * @param id 主键
     * @return 记录
     */
    @Override
    public FootTeam get(Serializable id) {
        return footTeamMapper.findById(id);
    }

    /**
     * 查询
     *
     * @param entityname         实体类名
     * @param map                参数
     * @param footTeamSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootTeamSearchForm footTeamSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footTeamSearchForm);
        Page<FootTeam> page = PageHelper.startPage(footTeamSearchForm.getPageIndex(), footTeamSearchForm.getPageSize());
        List<FootTeam> list = this.findall(footTeamSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param footTeamSearchForm 条件
     * @param request            请求
     */
    @Override
    public void deleteAll(FootTeamSearchForm footTeamSearchForm, HttpServletRequest request) {
        if(footTeamSearchForm.getSelectIds() != null){
            String[] result = footTeamSearchForm.getSelectIds().split(Constants.COMMA);
            for(String id: result){
                this .delete(Long.parseLong(id), request);
            }
        }
    }
}
